package com.ruoyi.web.controller.member.service.Impl;

import com.ruoyi.common.constant.MemberCreditConstants;
import com.ruoyi.common.constant.MemberRechargeConstants;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.DO.member.MemberBalanceRecordDO;
import com.ruoyi.common.entity.DO.member.MemberCreditRecordDO;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.VO.member.*;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.member.mapper.IBackMemberBalanceRecordMapper;
import com.ruoyi.web.controller.member.mapper.IBackMemberCreditRecordMapper;
import com.ruoyi.web.controller.member.mapper.IBackMemberMapper;
import com.ruoyi.web.controller.member.service.IBackMemberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class BackMemberServiceImpl implements IBackMemberService {

    @Resource
    private IBackMemberMapper memberMapper;

    @Resource
    private IBackMemberCreditRecordMapper backMemberCreditRecordMapper;

    @Resource
    private IBackMemberBalanceRecordMapper backMemberBalanceRecordMapper;

    @Override
    public List<MemberVO> searchList(MemberSearchVO memberSearchVO) {
        return memberMapper.searchList(memberSearchVO);
    }

    @Override
    public List<MemberExportVO> searchMemberExportList(MemberSearchVO memberSearchVO) {
        return memberMapper.searchMemberExportList(memberSearchVO);
    }

    @Override
    public MemberDO selectById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void edit(MemberVO memberVO) {
        if (StringUtils.isNotEmpty(memberVO.getIds())) {
            memberVO.setIdArr(Convert.toLongArray(memberVO.getIds()));
            if (memberVO.getIdArr().length > 1) {
                memberMapper.multiUpdate(memberVO);
            } else {
                memberVO.setId(memberVO.getIdArr()[0]);
                MemberDO member = memberMapper.selectByPrimaryKey(memberVO.getId());
                if(member == null){
                    throw new BusinessException("没找到该会员！");
                }
                memberMapper.updateByPrimaryKeySelective(member);
            }
        }else{
            MemberDO member = memberMapper.selectByPrimaryKey(memberVO.getId());
            if(member == null){
                throw new BusinessException("没找到该会员！");
            }
            member.setUserName(memberVO.getUserName());
            member.setSex(memberVO.getSex());
            member.setPhone(memberVO.getPhone());
            member.setEmail(memberVO.getEmail());
            memberMapper.updateByPrimaryKeySelective(member);
        }

    }

    @Override
    @Transactional
    public void editCredit(MemberVO memberVO) {
        MemberDO memberInfo = memberMapper.selectByPrimaryKey(memberVO.getId());
        if(null == memberInfo){
            throw new BusinessException("未找到该会员！");
        }
        if( 0 == memberVO.getCredit()) {
            return;
        }
        Integer newCredit = memberInfo.getCredit()+memberVO.getCredit();
        if( 0 > newCredit) {
            throw new BusinessException("扣减积分导致会员积分为负值，请重新设置！");
        }
        MemberCreditRecordDO memberCreditRecordDO = new MemberCreditRecordDO();
        if(memberVO.getCredit()<0) {
            //平台扣减积分
            memberCreditRecordDO.setRemark("系统扣除积分，扣减："+memberVO.getCredit()+"分，剩余："+newCredit+"分");
            memberCreditRecordDO.setChangeType(MemberCreditConstants.ChangeTypeEnum.DECREASE.getValue());
        }else {
            //平台赠送积分
            memberCreditRecordDO.setRemark("系统赠送积分，赠送："+memberVO.getCredit()+"分，剩余："+newCredit+"分");
            memberCreditRecordDO.setChangeType(MemberCreditConstants.ChangeTypeEnum.INCREASE.getValue());
        }
        //TODO:积分变动
        memberCreditRecordDO.setShopId(memberInfo.getShopId());
        memberCreditRecordDO.setRecordSn(OrderConstants.SnPrefix.CREDIT_MEMBER_BACK.getValue() + DateUtils.dateTimeNow() + NumberUtils.generateCode(4));
        memberCreditRecordDO.setType(MemberCreditConstants.TypeEnum.SYSTEM_INSERT.getValue());
        memberCreditRecordDO.setLinkModel(MemberCreditConstants.LinkModelEnum.BACK_CHANGE.getValue());
        memberCreditRecordDO.setLinkSn("");
        memberCreditRecordDO.setMemberId(memberInfo.getId());
        memberCreditRecordDO.setOldCredit(memberInfo.getCredit());
        memberCreditRecordDO.setChangeCredit(memberVO.getCredit());
        memberCreditRecordDO.setNewCredit(newCredit);
        memberCreditRecordDO.setCreateBy(memberVO.getUpdateBy());
        memberCreditRecordDO.setCreateTime(new Date());
        backMemberCreditRecordMapper.insertSelective(memberCreditRecordDO);
        MemberDO memberUpdate = new MemberDO();
        memberUpdate.setId(memberVO.getId());
        memberUpdate.setCredit(newCredit);
        memberUpdate.setUpdateTime(memberVO.getUpdateTime());
        memberUpdate.setUpdateBy(memberVO.getUpdateBy());
        memberMapper.updateByPrimaryKeySelective(memberUpdate);
    }

    @Override
    @Transactional
    public void editBalance(MemberVO memberVO) {
        MemberDO memberInfo = memberMapper.selectByPrimaryKey(memberVO.getId());
        if(null == memberInfo){
            throw new BusinessException("未找到该会员！");
        }
        if(null == memberVO.getBalance() || memberVO.getBalance().compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        BigDecimal newBalance = memberInfo.getBalance().add(memberVO.getBalance());
        if(newBalance.compareTo(BigDecimal.ZERO)<0) {
            throw new BusinessException("扣减余额导致会员余额为负值，请重新设置！");
        }
        MemberBalanceRecordDO memberBalanceRecordDO = new MemberBalanceRecordDO();
        if(memberVO.getBalance().compareTo(BigDecimal.ZERO)<0) {
            //平台扣减余额
            memberBalanceRecordDO.setRemark("系统扣除余额，扣除："+memberVO.getBalance()+"元，剩余："+newBalance+"元");
            memberBalanceRecordDO.setChangeType(MemberRechargeConstants.ChangeTypeEnum.DECREASE.getValue());
            memberBalanceRecordDO.setLinkModel(MemberRechargeConstants.LinkModelEnum.SYSTEM_DEDUCT.getValue());
        }else {
            //平台赠送余额
            memberBalanceRecordDO.setRemark("系统赠送余额，赠送："+memberVO.getBalance()+"元，剩余："+newBalance+"元");
            memberBalanceRecordDO.setChangeType(MemberRechargeConstants.ChangeTypeEnum.INCREASE.getValue());
            memberBalanceRecordDO.setLinkModel(MemberRechargeConstants.LinkModelEnum.SYSTEM_RECHARGE.getValue());
        }
        //TODO:余额变动
        memberBalanceRecordDO.setShopId(memberInfo.getShopId());
        memberBalanceRecordDO.setRecordSn(OrderConstants.SnPrefix.BALANCE_MEMBER_BACK.getValue() + DateUtils.dateTimeNow() + NumberUtils.generateCode(4));
        memberBalanceRecordDO.setType(MemberRechargeConstants.TypeEnum.SYSTEM_INSERT.getValue());
        memberBalanceRecordDO.setLinkSn("");
        memberBalanceRecordDO.setMemberId(memberInfo.getId());
        memberBalanceRecordDO.setOldBalance(memberInfo.getBalance());
        memberBalanceRecordDO.setChangeBalance(memberVO.getBalance());
        memberBalanceRecordDO.setNewBalance(newBalance);
        memberBalanceRecordDO.setCreateBy(memberVO.getUpdateBy());
        memberBalanceRecordDO.setCreateTime(new Date());
        backMemberBalanceRecordMapper.insertSelective(memberBalanceRecordDO);
        MemberDO memberUpdate = new MemberDO();
        memberUpdate.setId(memberVO.getId());
        memberUpdate.setBalance(newBalance);
        memberUpdate.setUpdateTime(memberVO.getUpdateTime());
        memberUpdate.setUpdateBy(memberVO.getUpdateBy());
        memberMapper.updateByPrimaryKeySelective(memberUpdate);
    }

    @Override
    public List<MemberBalanceRecordVO> searchBalanceRecordList(MemberBalanceRecordSearchVO memberBalanceRecordSearchVO) {
        List<MemberBalanceRecordVO> balanceRecordList = backMemberBalanceRecordMapper.searchList(memberBalanceRecordSearchVO);
        String logo;
        for (MemberBalanceRecordVO one : balanceRecordList
        ) {
            one.setOrderSn(one.getLinkSn());
            logo = MemberRechargeConstants.LinkModelEnum.match(one.getLinkModel()).getLogo();
            if (StringUtils.isNotEmpty(logo)) {
                one.setLogo(logo);
            }
        }
        return balanceRecordList;
    }

    @Override
    public List<MemberCreditRecordVO> searchCreditRecordList(MemberCreditRecordSearchVO memberCreditRecordSearchVO) {
        List<MemberCreditRecordVO> creditRecordList = backMemberCreditRecordMapper.searchList(memberCreditRecordSearchVO);
        String logo;
        for (MemberCreditRecordVO one : creditRecordList
        ) {
            one.setOrderSn(one.getLinkSn());
            logo = MemberRechargeConstants.LinkModelEnum.match(one.getLinkModel()).getLogo();
            if (StringUtils.isNotEmpty(logo)) {
                one.setLogo(logo);
            }
        }
        return creditRecordList;
    }

    @Override
    public int removeMemberByIds(String ids) {
        return memberMapper.deleteByIds(ids);
    }


}
